//编写读端，反序列化打印
#include <iostream>
#include <fstream>
#include"contacts.pb.h"

using namespace std;

void PrintContacts(const contacts2::Contacts& contacts)
{
    for(int j = 0; j < contacts.people_size(); j++)
    {
        const contacts2::PeopleInfo& people = contacts.people(j);
        cout << "------------联系人" << j+1 << "------------" << endl;
        cout << "联系人姓名： " << people.name() << endl;
        cout << "联系人年龄： " << people.age() << endl;
        for(int i = 0;i < people.phone_numbers_size();i++)
        {
            const contacts2::PeopleInfo_Phone& phone = people.phone_numbers(i);
            cout << "phone number" << i+1 << ":" << phone.number();
            cout << "     (" << phone.PhoneType_Name(phone.type()) << ")" << endl;
        }
        
        //若设置了any信息，并且类型为Address，则打印地址信息
        if(people.has_data() && people.data().Is<contacts2::Address>())
        {
            //1.创建Address对象
            contacts2::Address address;

            //2.将any信息解包到Address对象中
            people.data().UnpackTo(&address);

            //3.打印地址信息
            //若存在家庭地址
            if(!address.home_address().empty())
            {
                cout << "联系人家庭地址：" << address.home_address() << endl;
            }
            if(!address.office_address().empty())
            {
                cout << "联系人办公地址：" << address.office_address() << endl;
            }
        }

        //若设置了其他联系方式，则打印
        //other_contact_case()返回OtherContactCase枚举值，根据枚举值判断是哪一种联系方式
        switch(people.other_contact_case())
        {
            case contacts2::PeopleInfo::kQq:
                cout << "QQ号码：" << people.qq() << endl;
                break;
            case contacts2::PeopleInfo::kWechat:
                cout << "微信号码：" << people.wechat() << endl;
                break;
            default:
                break;
        }

        //打印备注信息
        if(!people.remark().empty())
        {
            cout << "联系人备注：" << endl;
        }
        else continue;

        for(auto it = people.remark().begin(); it != people.remark().end(); it++)
        {
            cout << "   标题: " << it->first << endl;
            cout << "   内容: " << it->second << endl;
        }
        
    }
}

int main()
{
    contacts2::Contacts contacts;
    //1.读取本地已存在文件
    fstream in("contacts.bin",ios::in | ios::binary);
    if(!contacts.ParseFromIstream(&in))
    {
        cout << "解析失败" << endl;
        return -1;
    }
    //2.打印通讯录表
    PrintContacts(contacts);

    //3.关闭文件
    in.close();
    return 0;
}
